import React, { useState, useEffect } from 'react';
import {
  Typography,
  Card,
  Table,
  Button,
  Space,
  Tag,
  Progress,
  message,
  Row,
  Col,
  Statistic,
  Input,
  Select,
  DatePicker,
  Tooltip,
  Avatar,
  Badge,
  Empty,
  Tabs,
  Timeline,
  Calendar,
  Modal,
  Form,
  List,
} from 'antd';
import {
  CalendarOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  TrophyOutlined,
  TeamOutlined,
  EyeOutlined,
  ExportOutlined,
  FilterOutlined,
  PlusOutlined,
  CheckOutlined,
  CloseOutlined,
} from '@ant-design/icons';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import locale from 'antd/locale/zh_CN';
import {
  getCheckinRecordsApi,
  getCheckinStatsApi,
  exportCheckinDataApi,
  getCheckinCalendarApi,
  createCheckinRecordApi,
  getCheckinActivitiesApi,
} from '../../../api/checkin';
import {
  RECORD_STATUS_OPTIONS,
  getStatusColor,
  getRecordStatusLabel,
  DEFAULTS,
  DATE_FORMATS,
} from '../CheckType';

// 设置dayjs为中文
dayjs.locale('zh-cn');

const { Title } = Typography;
const { Search } = Input;
const { Option } = Select;
const { RangePicker } = DatePicker;
const { TabPane } = Tabs;
const { TextArea } = Input;

const CheckinRecords = () => {
  // 状态管理
  const [checkinRecords, setCheckinRecords] = useState([]);
  const [stats, setStats] = useState({});
  const [loading, setLoading] = useState(false);
  const [searchParams, setSearchParams] = useState({
    keywords: '',
    status: undefined,
    dateRange: undefined,
    activityId: undefined,
  });
  const [activeTab, setActiveTab] = useState('myRecords');
  const [selectedDate, setSelectedDate] = useState(dayjs());

  // 日历功能相关状态
  const [calendarData, setCalendarData] = useState({});
  const [selectedDateData, setSelectedDateData] = useState([]);
  const [isCheckinModalVisible, setIsCheckinModalVisible] = useState(false);
  const [selectedSubActivity, setSelectedSubActivity] = useState(null);
  const [userActivities, setUserActivities] = useState([]);
  const [form] = Form.useForm();

  // 获取当前用户ID和姓名
  const getCurrentUserId = () => 1; // 临时写死，实际应该从登录状态获取
  const getCurrentUserName = () => "张三"; // 临时写死，实际应该从登录状态获取

  // 组件挂载时获取数据
  useEffect(() => {
    fetchCheckinRecords();
    fetchStats();
    fetchCalendarData();
  }, []);

  // 获取打卡记录
  const fetchCheckinRecords = async (params) => {
    try {
      setLoading(true);
      const response = await getCheckinRecordsApi({
        userId: getCurrentUserId(),
        ...params,
        pageNum: 1,
        pageSize: DEFAULTS.PAGE_SIZE,
      });
      
      if (response && response.code === '0') {
        // 后端已经返回了完整的打卡记录数据，无需额外处理
        const records = response.data?.list || [];
        
        // 直接使用后端返回的数据，补充一些默认值
        const processedRecords = records.map(record => ({
          ...record,
          // 确保字段存在，提供默认值
          activityName: record.activityName || '未知活动',
          activityType: record.activityType || 1,
          progress: record.progress || 0,
          dayNumber: record.dayNumber || 1,
          streak: record.streak || 1,
          isOnTime: record.isOnTime !== undefined ? record.isOnTime : true,
          images: record.images || [],
          content: record.notes || record.content || '',
        }));
        
        setCheckinRecords(processedRecords);
      } else {
        message.error(response.msg || '获取打卡记录失败');
      }
    } catch (error) {
      console.error('获取打卡记录失败:', error);
      message.error('获取打卡记录失败');
    } finally {
      setLoading(false);
    }
  };

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const response = await getCheckinStatsApi({
        userId: getCurrentUserId(),
      });

      if (response && response.code === '0') {
        setStats(response.data || {});
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
    }
  };

  // 获取所有可用的活动（简化版：查询所有进行中的活动）
  const fetchUserActivities = async () => {
    try {
      const response = await getCheckinActivitiesApi({
        pageNum: 1,
        pageSize: 100, // 获取所有活动
        status: 1, // 只获取进行中的活动
      });

      console.log('活动列表API响应:', response);

      // 支持不同的响应格式
      if (response && (response.code === '0' || response.code === 200 || response.code === '200')) {
        // PageInfo结构: { list: [...], total: 10, page: 1, pageSize: 10 }
        const pageData = response.data;
        const activities = pageData?.list || pageData || [];
        setUserActivities(activities);
        console.log('设置活动列表:', activities);
        console.log('活动数量:', activities.length);
      } else {
        console.error('获取活动列表失败:', response);
        message.error(response.msg || response.message || '获取活动列表失败');
      }
    } catch (error) {
      console.error('获取活动列表失败:', error);
      message.error('获取活动列表失败');
    }
  };

  // 获取日历数据
  const fetchCalendarData = async () => {
    try {
      setLoading(true);
      const response = await getCheckinCalendarApi({
        userId: getCurrentUserId(),
        year: selectedDate.year(),
        month: selectedDate.month() + 1,
      });

      if (response && response.code === '0') {
        // 后端返回的数据结构应该是按日期分组的活动数组
        // 格式: { "2024-01-01": [{ activityId, activityName, status, ... }], ... }
        const calendarData = response.data || {};

        // 确保每个日期的数据都是数组格式
        const processedData = {};
        Object.keys(calendarData).forEach(date => {
          const dayData = calendarData[date];
          if (Array.isArray(dayData)) {
            processedData[date] = dayData;
          } else {
            // 如果后端返回的是数字（打卡次数），转换为空数组
            processedData[date] = [];
          }
        });

        setCalendarData(processedData);
        console.log('日历数据:', processedData);
      } else {
        message.error(response.msg || '获取日历数据失败');
      }
    } catch (error) {
      console.error('获取日历数据失败:', error);
      message.error('获取日历数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理日期选择
  const handleDateSelect = (date) => {
    setSelectedDate(date);
    const dateKey = date.format(DATE_FORMATS.DATE);
    const dayData = calendarData[dateKey] || [];
    setSelectedDateData(dayData);
  };

  // 处理月份变化
  const handlePanelChange = (date) => {
    setSelectedDate(date);
    fetchCalendarData();
  };

  // 处理快速打卡
  const handleQuickCheckin = (activity) => {
    setSelectedSubActivity(activity);
    setIsCheckinModalVisible(true);
    form.resetFields();
  };

  // 处理打卡提交
  const handleCheckinSubmit = async () => {
    try {
      const values = await form.validateFields();

      const checkinData = {
        activityId: values.activityId,
        activityName: selectedSubActivity.title,
        userId: getCurrentUserId(),
        userName: getCurrentUserName(),
        checkinDate: selectedDate.format(DATE_FORMATS.DATE),
        notes: values.notes,
      };

      const response = await createCheckinRecordApi(checkinData);

      if (response && response.code === '0') {
        message.success('打卡成功！');
        setIsCheckinModalVisible(false);
        setSelectedSubActivity(null);
        fetchCalendarData();
        fetchStats();
        fetchCheckinRecords();
      } else {
        message.error(response.msg || '打卡失败');
      }
    } catch (error) {
      console.error('打卡失败:', error);
      message.error('打卡失败，请检查表单信息');
    }
  };

  // 处理搜索
  const handleSearch = () => {
    // 构建搜索参数，将时间区间拆分为开始和结束时间
    const params = {
      ...searchParams,
      startDate: searchParams.dateRange?.[0]?.format('YYYY-MM-DD'),
      endDate: searchParams.dateRange?.[1]?.format('YYYY-MM-DD'),
    };
    
    // 移除dateRange字段，避免传递给后端
    delete params.dateRange;
    
    fetchCheckinRecords(params);
  };

  // 处理重置搜索
  const handleResetSearch = () => {
    setSearchParams({
      keywords: '',
      type: undefined,
      status: undefined,
      dateRange: undefined,
      activityId: undefined,
    });
    setTimeout(() => {
      fetchCheckinRecords();
    }, 100);
  };

  // 处理导出数据
  const handleExportData = async () => {
    try {
      const response = await exportCheckinDataApi({
        userId: getCurrentUserId(),
        ...searchParams,
      });
      
      if (response && response.code === '0') {
        message.success('数据导出成功');
        // 处理文件下载
        const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `打卡记录_${dayjs().format('YYYY-MM-DD')}.xlsx`;
        link.click();
        window.URL.revokeObjectURL(url);
      } else {
        message.error(response.msg || '导出失败');
      }
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };


  // 日历单元格渲染
  const dateCellRender = (date) => {
    const dateKey = date.format(DATE_FORMATS.DATE);
    const dayData = calendarData[dateKey] || [];

    if (dayData.length === 0) {
      return null;
    }

    const totalCount = dayData.length;

    return (
      <div style={{ fontSize: 10, textAlign: 'center' }}>
        <Badge
          count={totalCount}
          size="small"
          style={{
            backgroundColor: '#52c41a' // 所有都是已完成状态
          }}
        />
        <div style={{ fontSize: 8, marginTop: 2 }}>
          {totalCount}
        </div>
      </div>
    );
  };

  // 表格列定义
  const columns = [
    {
      title: '打卡活动',
      key: 'activityName',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', fontSize: 14, marginBottom: 4 }}>
            {record.activityName || '未知活动'}
          </div>
        </div>
      ),
    },
    {
      title: '打卡时间',
      key: 'checkinDate',
      width: 350,
      render: (_, record) => {
        // 处理统一时间字段，添加错误处理
        let checkinDate = '未知日期';
        let createTime = '未知时间';
        // 只保留年月日
        if (record.checkinDate) {
          checkinDate = record.checkinDate.split(' ')[0]; // 提取年月日部分
        }
        createTime = record.createTime;
        return (
          <div>
            <div>打卡日期：{checkinDate}</div>
            <div>打卡时间：{createTime}</div>
          </div>
        );
      }
    },
    {
      title: '打卡内容',
      key: 'checkinContent',
      width: 400,
      render: (_, record) => (
        <div>
          {(record.content || record.notes) ? (
            <div style={{ fontSize: 12, color: '#666' }}>
              {record.content || record.notes}
            </div>
          ) : (
            <div style={{ fontSize: 12, color: '#999' }}>
              无备注内容
            </div>
          )}
          {record.duration && (
            <div style={{ marginTop: 4 }}>
              <Tag color="green">时长: {record.duration} 分钟</Tag>
            </div>
          )}
          {record.images && record.images.length > 0 && (
            <div style={{ marginTop: 8 }}>
              <Tag color="blue">图片: {record.images.length} 张</Tag>
            </div>
          )}
        </div>
      ),
    },
    {
      title: '进度',
      key: 'progress',
      width: 150,
      render: (_, record) => (
        <div>
          <div style={{ marginBottom: 8 }}>
            <Progress
              percent={record.progress || 0}
              size="small"
              status={record.progress >= 100 ? 'success' : 'active'}
            />
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            第 {record.dayNumber || 1} 天
          </div>
          <div style={{ fontSize: 12, color: '#666' }}>
            连续: {record.streak || 1} 天
          </div>
          {record.duration && (
            <div style={{ fontSize: 12, color: '#666' }}>
              练习: {record.duration} 分钟
            </div>
          )}
        </div>
      ),
    },
  ];

  // 统计卡片数据
  const statisticItems = [
    {
      key: 'totalCheckins',
      title: '总打卡次数',
      value: stats.totalCheckins || 0,
      suffix: '次',
      prefix: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
    },
    {
      key: 'thisMonth',
      title: '本月打卡',
      value: stats.thisMonthCheckins || 0,
      suffix: '次',
      prefix: <CalendarOutlined style={{ color: '#1890ff' }} />,
    },
    {
      key: 'streak',
      title: '最长连续',
      value: stats.maxStreak || 0,
      suffix: '天',
      prefix: <TrophyOutlined style={{ color: '#faad14' }} />,
    },
    {
      key: 'onTimeRate',
      title: '准时率',
      value: stats.onTimeRate || 0,
      suffix: '%',
      prefix: <ClockCircleOutlined style={{ color: '#722ed1' }} />,
    },
  ];

  // 日历页面的统计卡片数据
  const calendarStatisticItems = [
    {
      key: 'todayTasks',
      title: '今日任务',
      value: selectedDateData.length,
      suffix: '个',
      prefix: <CalendarOutlined style={{ color: '#1890ff' }} />,
    },
    {
      key: 'completedToday',
      title: '已完成',
      value: selectedDateData.length, // 所有都是已完成状态
      suffix: '个',
      prefix: <CheckCircleOutlined style={{ color: '#52c41a' }} />,
    },
    {
      key: 'pendingToday',
      title: '待完成',
      value: 0, // 没有待完成状态
      suffix: '个',
      prefix: <ClockCircleOutlined style={{ color: '#faad14' }} />,
    },
    {
      key: 'streak',
      title: '连续打卡',
      value: stats.currentStreak || 0,
      suffix: '天',
      prefix: <TrophyOutlined style={{ color: '#722ed1' }} />,
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面头部 */}
      <Title level={2} style={{ marginBottom: '24px' }}>
        打卡记录
      </Title>
      <Title level={4} type="secondary" style={{ marginBottom: '32px' }}>
        查看您的打卡记录、统计数据和日历视图
      </Title>
      
      <div style={{ marginBottom: '24px', textAlign: 'right' }}>
        <Button
          type="primary"
          icon={<ExportOutlined />}
          onClick={handleExportData}
        >
          导出数据
        </Button>
      </div>

      {/* 统计卡片 */}
      <Row gutter={16} style={{ marginBottom: 24 }}>
        {statisticItems.map(item => (
          <Col key={item.key} span={6}>
            <Card>
              <Statistic
                title={item.title}
                value={item.value}
                suffix={item.suffix}
                prefix={item.prefix}
              />
            </Card>
          </Col>
        ))}
      </Row>

      {/* 搜索和筛选 */}
      <Card style={{ marginBottom: 24 }}>
        <Row gutter={16} align="middle">
          <Col span={6}>
            <Search
              placeholder="搜索活动名称"
              value={searchParams.keywords}
              onChange={(e) => setSearchParams(prev => ({ ...prev, keywords: e.target.value }))}
              onSearch={handleSearch}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="记录状态"
              value={searchParams.status}
              onChange={(value) => setSearchParams(prev => ({ ...prev, status: value }))}
              allowClear
              style={{ width: '100%' }}
            >
              {RECORD_STATUS_OPTIONS.map(status => (
                <Option key={status.value} value={status.value}>
                  {status.label}
                </Option>
              ))}
            </Select>
          </Col>
          <Col span={6}>
            <RangePicker
              placeholder={['开始日期', '结束日期']}
              value={searchParams.dateRange}
              onChange={(dates) => setSearchParams(prev => ({ ...prev, dateRange: dates }))}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={4}>
            <Space>
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleResetSearch}>
                重置
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 主要内容区域 */}
      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab="打卡记录" key="myRecords">
          <Card title="打卡记录列表">
            {checkinRecords.length > 0 ? (
              <Table
                columns={columns}
                dataSource={checkinRecords}
                loading={loading}
                rowKey="id"
                pagination={{
                  total: checkinRecords.length,
                  pageSize: DEFAULTS.PAGE_SIZE,
                  showSizeChanger: true,
                  showQuickJumper: true,
                  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
                }}
              />
            ) : (
              <Empty
                description="暂无打卡记录"
                style={{ padding: '60px 0' }}
              />
            )}
          </Card>
        </TabPane>
        
        <TabPane tab="打卡日历" key="calendar">
          <div style={{ padding: '24px' }}>
            {/* 日历页面头部 */}
            <Title level={2} style={{ marginBottom: '24px' }}>
              打卡日历
            </Title>
            <Title level={4} type="secondary" style={{ marginBottom: '32px' }}>
              在日历上查看待打卡事项，快速进行打卡操作
            </Title>

            {/* 日历统计卡片 */}
            <Row gutter={16} style={{ marginBottom: 24 }}>
              {calendarStatisticItems.map(item => (
                <Col key={item.key} span={6}>
                  <Card>
                    <Statistic
                      title={item.title}
                      value={item.value}
                      suffix={item.suffix}
                      prefix={item.prefix}
                    />
                  </Card>
                </Col>
              ))}
            </Row>

            <Row gutter={24}>
              {/* 左侧日历 */}
              <Col span={16}>
                <Card title="打卡日历" loading={loading}>
                  <Calendar
                    value={selectedDate}
                    onSelect={handleDateSelect}
                    onPanelChange={handlePanelChange}
                    dateCellRender={dateCellRender}
                    fullscreen={false}
                    locale={locale.Calendar}
                    headerRender={({ value, type, onChange, onTypeChange }) => {
                      const start = 0;
                      const end = 12;
                      const monthOptions = [];

                      const current = value.clone();
                      const localeData = value.localeData();
                      const months = [];
                      for (let i = 0; i < 12; i++) {
                        current.month(i);
                        months.push(localeData.monthsShort(current));
                      }

                      for (let i = start; i < end; i++) {
                        monthOptions.push(
                          <Select.Option key={i} value={i} className="month-item">
                            {months[i]}
                          </Select.Option>
                        );
                      }

                      const year = value.year();
                      const month = value.month();
                      const options = [];
                      for (let i = year - 10; i < year + 10; i += 1) {
                        options.push(
                          <Select.Option key={i} value={i} className="year-item">
                            {i}
                          </Select.Option>
                        );
                      }

                      return (
                        <div style={{ padding: 8 }}>
                          <Row gutter={8}>
                            <Col>
                              <Select
                                size="small"
                                dropdownMatchSelectWidth={false}
                                className="my-year-select"
                                value={year}
                                onChange={(newYear) => {
                                  const now = value.clone().year(newYear);
                                  onChange(now);
                                }}
                              >
                                {options}
                              </Select>
                            </Col>
                            <Col>
                              <Select
                                size="small"
                                dropdownMatchSelectWidth={false}
                                value={month}
                                onChange={(newMonth) => {
                                  const now = value.clone().month(newMonth);
                                  onChange(now);
                                }}
                              >
                                {monthOptions}
                              </Select>
                            </Col>
                          </Row>
                        </div>
                      );
                    }}
                  />
                </Card>
              </Col>

              {/* 右侧日期详情 */}
              <Col span={8}>
                <Card
                  title={`${selectedDate.format('YYYY年MM月DD日')} 打卡详情`}
                  extra={
                    <Button
                      type="primary"
                      size="small"
                      icon={<PlusOutlined />}
                      onClick={async () => {
                        // 先加载活动列表
                        await fetchUserActivities();

                        // 直接显示打卡模态框
                        setIsCheckinModalVisible(true);
                      }}
                    >
                      快速打卡
                    </Button>
                  }
                >
                  {selectedDateData.length > 0 ? (
                    <List
                      size="small"
                      dataSource={selectedDateData}
                      renderItem={(item) => (
                        <List.Item
                          actions={[
                            <Tag color="success">已完成</Tag>
                          ]}
                        >
                          <List.Item.Meta
                            avatar={
                              <Avatar size="small" />
                            }
                            title={
                              <div>
                                <div style={{ fontWeight: 'bold' }}>{item.activityName}</div>
                              </div>
                            }
                            description={
                              <div>
                                <Tag color="success" size="small">
                                  已完成
                                </Tag>
                                <div style={{ marginTop: 4 }}>
                                  <Progress
                                    percent={item.progress || 0}
                                    size="small"
                                    showInfo={false}
                                  />
                                  <span style={{ fontSize: 12, color: '#666' }}>
                                    进度: {item.completedDays || 0}/{item.targetDays || 0} 天
                                  </span>
                                </div>
                              </div>
                            }
                          />
                        </List.Item>
                      )}
                    />
                  ) : (
                    <Empty
                      description="该日期暂无打卡任务"
                      style={{ padding: '40px 0' }}
                    />
                  )}
                </Card>
              </Col>
            </Row>
          </div>
        </TabPane>
        
        <TabPane tab="统计图表" key="charts">
          <Card title="打卡统计图表">
            <div style={{ textAlign: 'center', padding: '40px 0', color: '#999' }}>
              统计图表功能开发中...
            </div>
          </Card>
        </TabPane>
      </Tabs>

      {/* 快速打卡模态框 */}
      <Modal
        title={`快速打卡 - ${selectedSubActivity?.title || '选择活动'}`}
        visible={isCheckinModalVisible}
        onCancel={() => {
          setIsCheckinModalVisible(false);
          setSelectedSubActivity(null);
          setUserActivities([]); // 清空活动列表
        }}
        footer={[
          <Button
            key="cancel"
            onClick={() => {
              setIsCheckinModalVisible(false);
              setSelectedSubActivity(null);
              setUserActivities([]); // 清空活动列表
            }}
          >
            取消
          </Button>,
          <Button
            key="submit"
            type="primary"
            onClick={handleCheckinSubmit}
          >
            打卡
          </Button>,
        ]}
        width={500}
        destroyOnClose
      >
        <Form
          form={form}
          layout="vertical"
        >
          <Form.Item
            label="打卡日期"
          >
            <Input
              value={selectedDate.format(DATE_FORMATS.DATE)}
              disabled
            />
          </Form.Item>

          <Form.Item
            label="活动信息"
            name="activityId"
            rules={[{ required: true, message: '请选择要打卡的活动' }]}
          >
            <Select
              placeholder="请选择要打卡的活动"
              value={selectedSubActivity?.id}
              onChange={(value) => {
                const activity = userActivities.find(item => item.id === value);
                setSelectedSubActivity(activity);
              }}
            >
              {userActivities
                .filter(item => item.status === 1)
                .map(activity => (
                  <Option key={activity.id} value={activity.id}>
                    {activity.title}
                  </Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="打卡备注"
            name="notes"
          >
            <TextArea
              rows={3}
              placeholder="请输入打卡备注内容（可选）"
              maxLength={500}
              showCount
            />
          </Form.Item>

          <div style={{ textAlign: 'center', color: '#666', fontSize: 12 }}>
            <p>💡 提示：打卡后将自动更新进度和连续打卡天数</p>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default CheckinRecords; 